import {Button, Card, Form, Modal, Space, Typography} from "@douyinfe/semi-ui";
import {IconSend} from "@douyinfe/semi-icons";
import {
    generateInputLayout,
    generateSelectLayout,
    generateSliderLayout,
    InputItem,
    SelectItem,
    SliderItem
} from "./components/FormLayout.tsx";
import SectionComponent from "./components/SectionComponent.tsx";
import {useRef, useState} from "react";
import {
    addPredict,
    getFormattedDateWithLocale,
    getLevelByPercent,
    PredictTag, setNowPredictKey,
} from "../../api/storage/ApiPredict.ts";
import STTPopOver from "./components/Popover.tsx";
import {analysisForm} from "../../api/ApiAIAnalysis.ts";
import PredictResult from "./PredictResult.tsx";


const baseForm: { input: InputItem[], select: SelectItem[] } = {
    input: [{label: "年龄", field: "Age", placeholder: "请输入年龄"},
        {label: "身高（厘米）", field: "Height", placeholder: "请输入身高"},
        {label: "体重（公斤）", field: "Weight", placeholder: "请输入体重"}],
    select: [
        {
            label: "性别", field: "Gender", placeholder: "请选择性别",
            options: [{value: 0, text: "男"}, {value: 1, text: "女"}]
        },
        {
            label: "教育程度", field: "EducationLevel", placeholder: "请选择受教育水平",
            options: [
                {value: 0, text: "中小学以下或无教育经历"}, {value: 1, text: "高中与中专学历"},
                {value: 2, text: "本科与大专学历"}, {value: 3, text: "硕士及以上"}]
        },
    ]
}
const lifeForm: { select: SelectItem[] } = {
    select: [
        {
            label: "是否吸烟", field: "Smoking", placeholder: "请选择是否吸烟",
            options: [{value: 1, text: "是"}, {value: 0, text: "否"}]
        },
        {
            label: "是否饮酒", field: "AlcoholConsumption", placeholder: "请选择是否饮酒",
            options: [{value: 1, text: "是"}, {value: 0, text: "否"}]
        },
        {
            label: "阿尔茨海默病家族史", field: "FamilyHistoryAlzheimers", placeholder: "请选择是否家族史病例",
            options: [{value: 1, text: "有"}, {value: 0, text: "无"}]
        },
        {
            label: "心血管疾病", field: "CardiovascularDisease", placeholder: "请选择是否疾病情况",
            options: [{value: 1, text: "有"}, {value: 0, text: "无"}]
        },
        {
            label: "糖尿病", field: "Diabetes", placeholder: "请选择是否有糖尿病",
            options: [{value: 1, text: "有"}, {value: 0, text: "无"}]
        },
        {
            label: "抑郁症", field: "Depression", placeholder: "请选择是否有抑郁症",
            options: [{value: 1, text: "有"}, {value: 0, text: "无"}]
        },
        {
            label: "头部受伤史", field: "HeadInjury", placeholder: "请选择是否有头部受伤史",
            options: [{value: 1, text: "有"}, {value: 0, text: "无"}]
        },
        {
            label: "高血压", field: "Hypertension", placeholder: "请选择是否有高血压",
            options: [{value: 1, text: "有"}, {value: 0, text: "无"}]
        }
    ]
}
const habitForm: { slider: SliderItem[] } = {
    slider: [
        {label: "身体活动量（每周运动1小时记1分）", field: "PhysicalActivity"},
        {label: "饮食质量", field: "DietQuality"},
        {label: "睡眠质量", field: "SleepQuality"},
    ]
}
const mentalForm: { select: SelectItem[] } = {
    select: [
        {
            label: "是否感觉最近记忆力有下降", field: "MemoryComplaints", placeholder: "请选择是否有记忆方面的下降",
            options: [{value: 1, text: "是"}, {value: 0, text: "否"}]
        },
        {
            label: "行为问题", field: "BehavioralProblems", placeholder: "请选择是否存在行为问题",
            options: [{value: 1, text: "是"}, {value: 0, text: "否"}]
        },
        {
            label: "是否有困惑、糊涂症状", field: "Confusion", placeholder: "请选择是否有困惑、糊涂症状",
            options: [{value: 1, text: "是"}, {value: 0, text: "否"}]
        },
        {
            label: "是否有空间方向定向障碍情况",
            field: "Disorientation",
            placeholder: "请选择是否有空间方向定向障碍情况",
            options: [{value: 1, text: "是"}, {value: 0, text: "否"}]
        },
        {
            label: "是否有性格改变", field: "PersonalityChanges", placeholder: "请选择是否有性格改变",
            options: [{value: 1, text: "是"}, {value: 0, text: "否"}]
        },
        {
            label: "是否难以完成生活任务",
            field: "DifficultyCompletingTasks",
            placeholder: "请选择是否难以完成生活任务",
            options: [{value: 1, text: "是"}, {value: 0, text: "否"}]
        },
        {
            label: "是否健忘", field: "Forgetfulness", placeholder: "请选择是否健忘",
            options: [{value: 1, text: "是"}, {value: 0, text: "否"}]
        }
    ]
}
const medicalForm: { input: InputItem[] } = {
    input: [
        {label: "收缩压 MmHg（毫米汞柱）", field: "SystolicBP", placeholder: "请输入收缩压"},
        {label: "舒张压 MmHg（毫米汞柱）", field: "DiastolicBP", placeholder: "请输入舒张压"},
        {label: "总胆固醇 TC（mg/dL）", field: "CholesterolTotal", placeholder: "请输入总胆固醇"},
        {label: "低密度脂蛋白胆固醇（mg/dL）", field: "CholesterolLDL", placeholder: "请输入低密度脂蛋白胆固醇"},
        {label: "高密度脂蛋白胆固醇（mg/dL）", field: "CholesterolHDL", placeholder: "请输入高密度脂蛋白胆固醇"},
        {label: "胆固醇甘油三酯（mg/dL）", field: "CholesterolTriglycerides", placeholder: "请输入甘油三酯"},
        {
            label: "简易精神状态检查表评分 0~30分",
            field: "MMSE",
            placeholder: "请输入评分"
        },
        {label: "日常生活活动能力表评分 1~10分", field: "ADL", placeholder: "请输入评分"},
        {label: "功能独立性评测 1~7", field: "FunctionalAssessment", placeholder: "请输入评分"}
    ]
}
const Predict = (props: { changeToAIPageCall: () => void }) => {
    const formRef = useRef<Form>(null);
    const {Text} = Typography;
    const [showResult, setShowResult] = useState(false);
    const setFormValue = (field: string, value: string | number) => {
        if (formRef.current) {
            formRef.current.formApi.setValue(field, value);
        }
    }
    const onAnalysisClick = () => {
        if (formRef.current) {
            const json = formRef.current.formApi.getValues()
            console.log(json)
            analysisForm(json).then(r => console.log(r.json().then(value => {
                    console.log(value)
                    const risks = value.message.risks;
                    const items: PredictTag[] = [];
                    for (const key in risks) {
                        items.push({
                            key,
                            content: risks[key]
                        });
                    }
                    if (value.result == "success") {
                        const predict = {
                            key: "",//这里由其他文件中生成
                            condition: value.message.condition,
                            percent: value.message.possibility,
                            riskLevel: getLevelByPercent(value.message.possibility),
                            time: getFormattedDateWithLocale(),
                            prompt: value.message.prompt,
                            tags: items
                        }
                        setNowPredictKey(addPredict(predict))
                        setShowResult(true)
                    }
                }
            ))).catch()
        }

    }
    const fields = () => (<>
        <SectionComponent name={"基本信息"}>
            {generateInputLayout(8, baseForm.input)}
            {generateSelectLayout(8, baseForm.select)}
        </SectionComponent>
        <SectionComponent name={"生活情况"}>
            {generateSelectLayout(8, lifeForm.select)}
        </SectionComponent>
        <SectionComponent name={"日常习惯"}>
            {generateSliderLayout(12, habitForm.slider)}
        </SectionComponent>
        <SectionComponent name={"心理状态"}>
            {generateSelectLayout(8, mentalForm.select)}
        </SectionComponent>
        <SectionComponent name={"补充医学情况（非必填）"}>
            {generateInputLayout(8, medicalForm.input)}
        </SectionComponent>
    </>);
    const [visible, setVisible] = useState(false);
    const [title, setShowTitle] = useState("用户协议");
    const [text, setShowText] = useState("加载中...");
    const showDialog = (id: number) => {
        let path = ''
        if (id == 0) {
            setShowTitle("用户协议")
            path = 'assets/user.md'
        } else {
            setShowTitle("隐私策略")
            path = 'assets/privacy.md'
        }
        const fetchMarkdown = async () => {
            try {
                const response = await fetch(path);
                if (response.ok) {
                    return await response.text()
                }
            } catch { /* empty */
            }
            return "加载失败"
        };
        fetchMarkdown().then(value => setShowText(value));
        setVisible(true);
    };
    const handleOk = () => {
        setVisible(false);
    };
    const handleCancel = () => {
        setVisible(false);
    };
    return (
        (showResult ? (
            <PredictResult show={showResult} changeToAIPageCall={props.changeToAIPageCall}/>
        ) : (
            <div style={{flexGrow: 1, margin: 20}}>
                <Card bordered={true} headerLine={true}>
                    <Form ref={formRef} component={fields}/>
                </Card>
                <Space style={{marginTop: 20}}>
                    <STTPopOver setFormValue={setFormValue}/>
                    <Button theme='solid' type='primary' icon={<IconSend/>} style={{width:200}} onClick={onAnalysisClick}>AI分析</Button>
                    <Text>点击AI分析即代表您已阅读并同意</Text>
                    <Text link={{}} onClick={() => {
                        showDialog(0)
                    }}>《用户协议》</Text>
                    <Text>与</Text>
                    <Text link={{}} onClick={() => {
                        showDialog(1)
                    }}>《隐私策略》</Text>
                </Space>
                <Modal
                    title={title}
                    visible={visible}
                    style={{width:"70%",height:"70%"}}
                    onOk={handleOk}
                    bodyStyle={{ overflow: 'auto', whiteSpace: 'pre-wrap' ,fontSize: 10}}
                    onCancel={handleCancel}
                    closeOnEsc={true}
                >
                    {text}
                </Modal>
            </div>
        ))
    )
}

export default Predict